package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate



/**
* @Title:
* @Description:
* @Param: 通用外呼规则自动下发规则
* @return: 十分钟执行一次
* @Author: TaoHao
* @Date: 2024/10/18
*/
class autoCurrencyRuleIssued implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoCurrencyRuleIssued.class);

    //任务下发主要方法
    void doCallBack(EliteBean eliteBean, String s, Map map, String s1) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        int deal_flag = 0; String objective_guid = "";String deal_result = "";
        //2.通用待下发任务处理（定时10分钟执行一次）
        if (KHDBConfig.getParam(eliteBean,"TYLOCK")=="OPEN"){

            log.debug("【通用规则下发名单开始】");
            //将锁开启
            String updatesql = '''update sysc_parameter set PARAMETERVALUE='CLOSE' where PARAMETER_ID='TYLOCK' ''';
            jt.update(updatesql);
            List accountList = eliteBean.chaxun_sql("SELECT a.rec_id,a.customerid,a.task_type,a.task_guid,c1.customer_guid FROM pa_Account_Information a LEFT JOIN customer c1 ON a.customerid = c1.CUSTOMER_ID WHERE 1=1 AND ( a.deal_flag = 0 OR a.deal_flag =- 2 ) AND ( a.thread_id IS NULL OR a.thread_id = '' ) ", "dataSource");
            for (int i = 0; i < accountList.size(); i++) {
                try {
                    long startTime = System.currentTimeMillis();
                    Map accountMap = accountList.get(i);
                    String rec_id = accountMap.get("rec_id");//处理任务主键
                    String customerid = accountMap.get("customerid");//资金账号
                    String customer_guid=accountMap.get("customer_guid");//客户ID
                    String mobile = accountMap.get("mobile");//联系号码
                    String task_type = accountMap.get("task_type");//任务类型编号

                    log.debug("【开始执行下发】资金账号：" + customerid + "|任务类型：" + task_type);

                    if (customer_guid == '' || customer_guid == null) {
                        deal_flag = -2;
                        deal_result = "下发失败-资金账号:" + customerid + ",根据资金账号在集中作业平台未找到客户信息";
                    }else {
                            //使用资金账号校验是否存在与资金账号同类型的任务
                            String checkTask = "";
                            String checkSameTask = "select e.elitetask_guid from elitetask e left join customer c on c.customer_guid=e.customer_guid  where c.customer_id='" + customerid + "'  and e.PA_TASKTYPE='" + task_type + "'";
                            List checkTaskRes = eliteBean.chaxun_sql(checkSameTask, "dataSource");
                            if (checkTaskRes.size() > 0) {
                                Map checkTaskMap = checkTaskRes.get(0);
                                checkTask = checkTaskMap.get("elitetask_guid");
                            }
                            if (!KHUtil.isNull(checkTask)) {
                                deal_flag = -1;
                                deal_result = "下发失败-资金账号:" + customerid + ",已存在相同类型的" +task_type  + "任务无需再次下发";
                            }else{

                                log.debug("【通用外呼规则】开始新客下发流程：" + customerid);
                                Map newCustomerManagerMap1 = newCustomerManager(eliteBean, customerid, customer_guid, task_type);
                                deal_flag = newCustomerManagerMap1.get("deal_flag").toInteger();
                                deal_result = newCustomerManagerMap1.get("deal_result");
                            }
                    }

                    //任务耗时统计
                    long endTime = System.currentTimeMillis();
                    String reOutIntermediarySql = "Update pa_Account_Information Set Deal_Time = Now(), Deal_Flag = " + deal_flag + ", Deal_Result = '" + deal_result + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = '" + rec_id + "'";
                    eliteBean.update(reOutIntermediarySql, "dataSource");
                    String pa_activity_batch_list='''Update pa_activity_batch_list set result_desc=?,result_code=? where  rec_id=? ''';
                    jt.update(pa_activity_batch_list,deal_result,deal_flag,rec_id);
                    log.debug("【执行结束】本次耗时:" + (endTime - startTime));
                } catch (Exception e) {
                    log.error("【执行结束】当前名单"+i+" 执行处理异常!", e);
                }
            }
            String updatesql2 = '''update sysc_parameter set PARAMETERVALUE='OPEN' where PARAMETER_ID='TYLOCK' ''';
            jt.update(updatesql2);

        }
    }



    //通用外呼任务下发
    public static Map<String, String> newCustomerManager(EliteBean eliteBean, String customerid, String customer_guid, String task_type) {
        boolean newCustDeal3;
        String deal_result = "";
        String deal_flag = "";
        String se_handlegroup_id = "";
        String se_handleby_id = "";
        String rule_rec_id = "";
        String staffname="";
        Map<String, String> map = new HashMap<String, String>();

        //内部居间人，根据名单渠道查询是否存在规则
        def findChannel = "Select Rule_Id, Rule_Name From Hst_Rule_Issue Where Rule_State = 1 And  Rule_Name='"+task_type+"' Order By Order_Adjustment Limit 1";
        List channelList = eliteBean.chaxun_sql(findChannel, "dataSource");
        //查询到渠道规则按照渠道规则下发
        int re_channelsize = channelList.size();
        log.debug("渠道规则条数：" + re_channelsize);
        if (re_channelsize > 0) {
            log.debug("内部居间人名单，且存在渠道规则");
            String rule_id = channelList.get(0).get("Rule_Id");//渠道规则编号

            //检查下发规则并初始化
            ruleAssignInit(eliteBean, rule_id);

            // (按渠道规则平均)取当前名单下发最少的坐席（不支持一人多组）
            def getAssginStaffSQL = "Select R1.Rec_Id, R2.Rolegroup_Id, R1.Staff_Id, R3.counselor_id,R3.staffname" +
                    "  From Hst_Rule_Issue_Control R1" +
                    "  Left Join Staffrolegroup R2" +
                    "    On R1.Staff_Id = R2.Staff_Id" +
                    "  Left Join Staff R3" +
                    "    On R1.Staff_Id = R3.Staff_Id" +
                    " Where Rule_Id = " + rule_id + "" +
                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')" +
                    " Order By Assign_Num,Staff_Id Limit 1";
            List getAssginStaffList = eliteBean.chaxun_sql(getAssginStaffSQL, "dataSource");

            if (getAssginStaffList.size() > 0) {
                Map getAssginStaffMap = getAssginStaffList.get(0);
                rule_rec_id = getAssginStaffMap.get("Rec_Id");
                se_handlegroup_id = getAssginStaffMap.get("Rolegroup_Id");
                se_handleby_id = getAssginStaffMap.get("Staff_Id");
                 staffname  = getAssginStaffMap.get("staffname");
                log.debug("[内部居间人名单,根据规则匹配到下发坐席为] Rolegroup_Id:" + se_handlegroup_id + " Staff_Id:" + se_handleby_id + "rule_id:" + rule_id);

                //居间人为内部人员，取渠道规则中名单较少的坐席，实现平均分配
                newCustDeal3 = newCustomerDeal(eliteBean, se_handlegroup_id, se_handleby_id,"ONA0KD", "", customer_guid, task_type, rule_rec_id, customerid);
                if (newCustDeal3) {
                    map.put("deal_flag", "1");
                    map.put("deal_result", "下发成功-资金账号:" + customerid + ",将名单平均下发至" + staffname);
                }
            } else {
                map.put("deal_flag", "-1");
                map.put("deal_result", "下发失败-资金账号:" + customerid + ",存在规则但未正确匹配到坐席");
            }

        } else {
            String defaultrule_id = '1';
            log.debug("内部居间人名单,但不存在渠道规则,需要将名单平均分配给电销坐席");
            //检查下发规则并初始化
            ruleAssignInit(eliteBean, defaultrule_id);
            // 默认平均分配，取当前名单下发最少的坐席（不支持一人多组）
            def getAverageStaffSQL = "Select R1.Rec_Id, R2.Rolegroup_Id, R1.Staff_Id, R3.counselor_id,R3.staffname" +
                    "  From Hst_Rule_Issue_Control R1" +
                    "  Left Join Staffrolegroup R2" +
                    "    On R1.Staff_Id = R2.Staff_Id" +
                    "  Left Join Staff R3" +
                    "    On R1.Staff_Id = R3.Staff_Id" +
                    " Where Rule_Id = " + defaultrule_id + "" +
                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')" +
                    " Order By Assign_Num,Staff_Id Limit 1";
            List getAverageStaffSQLList = eliteBean.chaxun_sql(getAverageStaffSQL, "dataSource");

            if (getAverageStaffSQLList.size() > 0) {
                Map getAverageStaffMap = getAverageStaffSQLList.get(0);
                rule_rec_id = getAverageStaffMap.get("Rec_Id");
                se_handlegroup_id = getAverageStaffMap.get("Rolegroup_Id");
                se_handleby_id = getAverageStaffMap.get("Staff_Id");
                staffname  = getAverageStaffMap.get("staffname");
                log.debug("[内部居间人名单,未找到渠道规则，按默认平均分配规则分配] Rolegroup_Id:" + se_handlegroup_id + " Staff_Id:" + se_handleby_id + "rule_id:" + defaultrule_id);

                newCustDeal3 = newCustomerDeal(eliteBean, se_handlegroup_id, se_handleby_id, "ONA0KD", "", customer_guid, task_type, rule_rec_id, customerid);
                if (newCustDeal3) {
                    map.put("deal_flag", "1");
                    map.put("deal_result", "下发成功-资金账号:" + customerid + ",未找到渠道规则，按默认平均分配规则分配至" + staffname);
                } else {
                    map.put("deal_flag", "-1");
                    map.put("deal_result", "下发失败-资金账号:" + customerid + ",默认平均分配失败");
                }
            } else {
                map.put("deal_flag", "-1");
                map.put("deal_result", "下发失败-资金账号:" + customerid + ",未找到默认平均分配规则");
            }
        }
        return map;
    }



    //创建任务(objective及eliteask),新客发送客户经理短信
    public static boolean newCustomerDeal(EliteBean eliteBean, String r_Rolegroup_Id, String r_Staff_Id, String node_id, String Objective_Guid, String Customer_Guid, String task_type, String Rec_Id, String customer_id) {
        boolean reFlag = true;
        // 生成相关ID
        String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
        String re_Objective_Guid = "";

        if (Objective_Guid == "") {
            re_Objective_Guid = "OBJE_" + Temp_Guid;
        } else {
            re_Objective_Guid = Objective_Guid;
        }
        String EliteTask_Guid = "TASK_" + Temp_Guid;
        String[] custTaskDealSQL = new String[6];

        try {
            if (Objective_Guid == '' || Objective_Guid == null) {
                // 插入Objective表
                custTaskDealSQL[1] = "Insert Into Objective" +
                        "  (Objective_Guid," +
                        "   Objectivetype_Id," +
                        "   Handleby_Id," +
                        "   Handlegroup_Id," +
                        "   Priority_Id," +
                        "   Expireddate," +
                        "   Customer_Guid," +
                        "   Objectivestatus," +
                        "   Iscontact," +
                        "   Trytimes," +
                        "   Successfulcontacttimes," +
                        "   Createdby," +
                        "   Createddate," +
                        "   Obstatus," +
                        "   Failure_Attempt," +
                        "   Contact_Customer_Guid," +
                        "   Passflag," +
                        "   Lastassigndate," +
                        "   Failstatus," +
                        "   Successstatus," +
                        "   Owner," +
                        "   Workorderframe_Id," +
                        "   Category," +
                        "   Forecastdate," +
                        "   Workorderid," +
                        "   Workordertype1," +
                        "   Workordertype2," +
                        "   Workordertype3," +
                        "   Workordertype4," +
                        "   Objectivesubstatus," +
                        "   Map_Id," +
                        "   Curstep_Id_Map," +
                        "   Max_Attempt," +
                        "   Nocontacttry," +
                        "   Allocation_Pool," +
                        "   Appointment," +
                        "   PA_TASKTYPE)" +
                        "Values" +
                        "  ('" + re_Objective_Guid + "'," +
                        "   'RE0TX1'," +
                        "   '" + r_Staff_Id + "'," +
                        "   '" + r_Rolegroup_Id + "'," +
                        "   'NORMAL'," +
                        "   Date_Add(Now(), Interval 1 Day)," +
                        "   '" + Customer_Guid + "'," +
                        "   'OPEN'," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   'SELITE'," +
                        "   Now()," +
                        "   'OPEN'," +
                        "   999," +
                        "   ''," +
                        "   0," +
                        "   Null," +
                        "   '0'," +
                        "   '0'," +
                        "   ''," +
                        "   'P200DM'," +
                        "   'CASE'," +
                        "   now()," +
                        "   Concat('PA', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
                        "   ''," +
                        "   ''," +
                        "   ''," +
                        "   ''," +
                        "   'OPEN'," +
                        "   'P200DM'," +
                        "   '" + node_id + "'," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   '" + task_type + "')";
            }
            // 插入EliteTask表
            custTaskDealSQL[2] = "Insert Into Elitetask" +
                    "  (Elitetask_Guid," +
                    "   Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Expectstarttime," +
                    "   Expectendtime," +
                    "   Obstatus," +
                    "   Recordstatus," +
                    "   Attempt," +
                    "   Max_Attempt," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Failure_Attempt," +
                    "   Comments," +
                    "   Customer_Guid," +
                    "   Localtrycount," +
                    "   Lastassigndate," +
                    "   Workorderframe_Id," +
                    "   Curstepstatus," +
                    "   Curstep_Id," +
                    "   Stepforecastdate," +
                    "   Curstep_Id_Map," +
                    "   Map_Id," +
                    "   Objectivesubstatus," +
                    "   Elitetaskstatus," +
                    "   Obflag,Maintaskstep_Id_Map," +
                    "   PA_TASKTYPE)" +
                    "Values" +
                    "  ('" + EliteTask_Guid + "'," +
                    "   '" + re_Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   Now()," +
                    "   Date_Add(Now(), Interval 3 Day)," +
                    "   'OPEN'," +
                    "   0," +
                    "   0," +
                    "   999," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   999," +
                    "   ''," +
                    "   '" + Customer_Guid + "'," +
                    "   0," +
                    "   Now()," +
                    "   ''," +
                    "   'OPEN'," +
                    "   'ONA0KD'," +
                    "   Now()," +
                    "   '" + node_id + "'," +
                    "   'P200DM'," +
                    "   'OPEN'," +
                    "   'OPEN'," +
                    "   1,'','" + task_type + "')";

            //渠道规则均分
            if (Rec_Id != "" && Rec_Id != null) {
                custTaskDealSQL[3] = "Update Hst_Rule_Issue_Control Set Assign_Num = Assign_Num + 1, Last_Check_Time = Now() Where Rec_Id = " + Rec_Id;
            }

            String eta_id = "";
            String re_path = "";

            //新增分配历史
            custTaskDealSQL[4] = "insert into hst_Service_hislist(sys_guid,CUSTOMER_ID,customer_guid,used_staffid,apply_time,MODIFIEDBY,context,Reviewer_staffid,Reviewer_time) VALUES(uuid(),'" + customer_id + "','" + Customer_Guid + "','" + r_Staff_Id + "',now(),'SELITE','通用任务自动下发','SELITE',now()) ";

            int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
            log.debug("新客户入库批量处理SQL返回结果：" + batchSQLResult.toString());


        } catch (Exception e) {
            log.error("新客户入库异常!", e);
            reFlag = false;
        }

        return reFlag;
    }


    //规则下发数据初始化
    public static boolean ruleAssignInit(EliteBean eliteBean, String Rule_Id) {
        boolean reFlag = true;

        //新增判断坐席B岗接任时间的逻辑截止状态、及离职人员默认不分配
        //A.-如果有离职人员 则直接关闭其分配状态-- 是否开启自动分配 0开启 1关闭
        String updatestaffstate1SQL = "update staff set auto_allocation=1 Where auto_allocation=0 And workstatus!='ONLINE'";
        eliteBean.update(updatestaffstate1SQL, "dataSource");

        //B.-如果有B岗角色接任时间到期 则更新企状态为自动开启分配 +清空时间维护
        String updatestaffstate2SQL = "update staff set auto_allocation=0,starttime=null,endtime=null Where auto_allocation=1  And starttime <now() And endtime<now()";
        eliteBean.update(updatestaffstate2SQL, "dataSource");

        // 初始化（1~4）下发记录表（这里默认按每天清零）
        // 1-查找当前规则配置的坐席
        String ruleStaffSQL = "Select Case When R1.Staff_Id Is Null Or R1.Staff_Id = '' Then R2.Staff_Id Else R1.Staff_Id End As ruleStaff" +
                " From Hst_Rule_Issue R1" +
                " Left Join (Select R4.Rule_Id, Group_Concat(Distinct R3.Staff_Id) As Staff_Id" +
                "    From Rolegroup R1" +
                "    Left Join Staffrolegroup R2 On R1.Rolegroup_Id = R2.Rolegroup_Id" +
                "    Left Join Staff R3 On R2.Staff_Id = R3.Staff_Id" +
                "    Left Join Hst_Rule_Issue R4 On Find_In_Set(R1.Rolegroup_Id, R4.Rolegroup) > 0" +
                "    Where R1.Status = 1 And ((R3.auto_allocation = 0) " +
                "    or (R3.auto_allocation = 1 And R3.starttime>now() And R3.endtime>now() And R3.starttime is not null And R3.endtime is not null)" +
                "    or (R3.auto_allocation = 1 And R3.starttime<now() And R3.endtime<now() And R3.starttime is not null And R3.endtime is not null))" +
                "    And R3.Workstatus = 'ONLINE'" +
                "    And R4.Rule_Id = " + Rule_Id + ") R2" +
                " On R1.Rule_Id = R2.Rule_Id And (R1.Staff_Id Is Null Or R1.Staff_Id = '')" +
                " Where R1.Rule_Id = " + Rule_Id + "";

        List ruleStaffList = eliteBean.chaxun_sql(ruleStaffSQL, "dataSource");

        Map ruleStaffMap = ruleStaffList.get(0);
        log.debug("ruleStaffMap:" + ruleStaffMap);
        String ruleStaff = ruleStaffMap.get("ruleStaff");
        log.debug("ruleStaff:" + ruleStaff);
        //处理Assign_Num
        def selectassignnumSQL = "select case when count(*)=0 then 0 else  round(sum(assign_num)/count(*)) end as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + "  And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
        def selectassignnumresult = eliteBean.chaxun_sql(selectassignnumSQL, "dataSource");
        def assignnum = 0;
        if (selectassignnumresult.size() > 0) {
            assignnum = selectassignnumresult.get(0).get("assignnum");
        }
        log.debug("assignnum:" + assignnum);

        // 2-将不在下发规则表中不存在的坐席补充，防止中途规则配置的人或组修改添加
        String insertStaffSQL = "Insert Into Hst_Rule_Issue_Control" +
                "  (Rule_Id, Staff_Id, Assign_Date, Assign_Num,assign_yynum, Last_Check_Time)" +
                "  Select " + Rule_Id + ", Staff_Id, Date_Format(Now(), '%Y-%m-%d'), '" + assignnum + "', 0, Now()" +
                "  From Staff" +
                "  Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "  And Staff_Id Not In (Select Staff_Id From Hst_Rule_Issue_Control Where Rule_Id = " + Rule_Id + " And Assign_Date = Date_Format(Now(), '%Y-%m-%d'))";
        log.debug("insertStaffSQL:" + insertStaffSQL);
        int newStaffNum = eliteBean.update(insertStaffSQL, "dataSource");
        log.debug("newStaffNum:" + newStaffNum);

        // 3-将不需要不满足下发的坐席删除，防止中途规则配置的人或组删除
        String deleteStaffSQL = "Delete From Hst_Rule_Issue_Control" +
                " Where Staff_Id Not In" +
                "       (Select Staff_Id" +
                "          From Staff" +
                "         Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "   And ((auto_allocation = 0) " +
                " 	or (auto_allocation = 1 And starttime>now() And endtime>now() And starttime is not null And endtime is not null)" +
                " 	or (auto_allocation = 1 And starttime<now() And endtime<now() And starttime is not null And endtime is not null))" +
                "   And Workstatus = 'ONLINE')" +
                "   And Rule_Id = " + Rule_Id + "" +
                "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
        log.debug("deleteStaffSQL:" + deleteStaffSQL);
        eliteBean.update(deleteStaffSQL, "dataSource");

        // 4-如果有新加的人员将规则坐席已下发数量全部归零
        /*
        if (newStaffNum > 0) {
            String updateAssignNum = "Update Hst_Rule_Issue_Control" +
                    "   Set Assign_Num = 0,assign_yynum = 0, Last_Check_Time = Now()" +
                    " Where Rule_Id = " + Rule_Id + "" +
                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
            eliteBean.update(updateAssignNum, "dataSource");
        }
        */
        return reFlag;
    }


}